package com.quanyan.club.task.tracker;

import com.github.ltsopensource.core.domain.Action;
import com.github.ltsopensource.tasktracker.Result;
import com.github.ltsopensource.tasktracker.runner.JobContext;
import com.github.ltsopensource.tasktracker.runner.JobRunner;
import com.quanyan.api.APIResponse;
import com.quanyan.club.entity.db.TbClubIntegralRule;
import com.quanyan.club.mapper.ClubYearActivityMapper;
import com.quanyan.club.mapper.TbClubIntegralRuleMapper;
import com.quanyan.club.service.ClubService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Administrator on 2016/7/27.
 *
 * 俱乐部积分任务逻辑处理
 */
@Component
public class ClubYearActivityJob implements JobRunner{
    private static final Logger logger = LoggerFactory.getLogger(ClubYearActivityJob.class);

    @Autowired
    private TbClubIntegralRuleMapper tbClubIntegralRuleMapper;

    @Autowired
    private ClubYearActivityMapper clubYearActivityMapper;

    @Override
    public Result run(JobContext jobContext) throws Throwable {
        try{
            logger.warn("--更新的俱乐部记录数任务开始了------");
            if(this.getActivityStartTime()!=0){
                return new Result(Action.EXECUTE_SUCCESS,"活动还没开始或已结束，无需执行该任务");
            }
            //活动期间批量刷新每天砸鸟蛋次数
            int count=clubYearActivityMapper.batchUpateClickTimes();
            logger.warn("--更新的俱乐部记录数------>>>>>"+count);
        }catch (Exception e){
            logger.warn("批量刷新每天砸鸟蛋次数失败！", e);
            return new Result(Action.EXECUTE_LATER, "批量刷新每天砸鸟蛋次数失败"+e.getMessage());
        }
        return new Result(Action.EXECUTE_SUCCESS,"俱乐部积分任务执行成功");
    }

    private int getActivityStartTime(){
        TbClubIntegralRule tbClubIntegralRule=tbClubIntegralRuleMapper.selectByPrimaryKey(7);
        String startTime=tbClubIntegralRule.getFinishGrade();
        String endTime=tbClubIntegralRule.getPoint();
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return this.compareDate(simpleDateFormat.parse(startTime),simpleDateFormat.parse(endTime));
        } catch (ParseException e) {
            e.printStackTrace();
            return 2;
        }
    }

    private int compareDate(Date start, Date end) {
        Date today=new Date();
        if(today.getTime()<start.getTime()){
            return 1;
        }
        if (today.getTime()>end.getTime()){
            return 2;
        }
        return 0;
    }
}
